package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Context {
    private String uri;
    private String absPath;
    private Map<String, Wrapper> wrappers = new HashMap<>();

    public Context(String uri, String absPath) {
        this.uri = uri;
        this.absPath = absPath;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getAbsPath() {
        return absPath;
    }

    public void setAbsPath(String absPath) {
        this.absPath = absPath;
    }

    public void init() {
        // 查找web.xml构建wrapper
        File file = new File(absPath, "web.xml");
        if (file.exists() || file.isFile()) {
            try {
                SAXReader saxReader = new SAXReader();
                Document document = saxReader.read(file);
                Element rootElement = document.getRootElement();
                List<Element> selectNodes = rootElement.selectNodes("//servlet");
                for (int i = 0; i < selectNodes.size(); i++) {
                    // 处理单个servlet
                    Element element = selectNodes.get(i);
                    // <servlet-name>lagou</servlet-name>
                    Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                    String servletName = servletnameElement.getStringValue();
                    // <servlet-class>server.LagouServlet</servlet-class>
                    Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                    String servletClass = servletclassElement.getStringValue();
                    // 根据servlet-name的值找到url-pattern
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    // /lagou
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                    // 获取servlet，构建wrapper
                    HttpServlet servlet = loadServlet(servletClass);
                    Wrapper wrapper = new Wrapper();
                    wrapper.setServlet(servlet);
                    wrapper.setUri(urlPattern);
                    wrappers.put(urlPattern, wrapper);
                }
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    }

    private HttpServlet loadServlet(String servletClass)  {
        String path = absPath + '/' + servletClass.replace(".", "/") + ".class";
        minicatClassLoader classLoader = new minicatClassLoader(servletClass);
        try {
            Class<?> aClass = classLoader.findClass(path);
            return (HttpServlet) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean process(Request request, Response response) throws Exception {
        String url = request.getUrl().substring(1);
        int i = url.indexOf('/');
        String contextUri = url.substring(0, i);
        if (!uri.equals(contextUri)) {
            return false;
        }

        String lastUri = url.substring(i);
        Wrapper wrapper = wrappers.get(lastUri);
        if (wrapper != null) {
            wrapper.getServlet().service(request, response);
            return true;
        } else {
            String staticPath = absPath + lastUri;
            // 判断是否有静态资源
            File file = new File(staticPath);
            if(file.exists() && file.isFile()) {
                response.outputHtml(file);
                return true;
            }
            return false;
        }
    }
}
